package fm.card.web;

import com.google.gson.Gson;
import com.mongodb.BasicDBObject;
import fm.card.entity.AES;
import fm.card.entity.PersonInfo;
import fm.controller.BaseController;
import fm.dao.MongoBaseDao;
import fm.exception.BizException;
import fm.mongo.MongoTable;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/person/card/")
public class CardController extends BaseController {
    @Autowired
    MongoBaseDao mongoBaseDao;

    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Map updateInfo(PersonInfo user) {
        Map res = new HashMap();
        try {
            Map param = new BasicDBObject("code", user.getCode()).toMap();
            PersonInfo info = (PersonInfo) mongoBaseDao.findOne(param, PersonInfo.class, MongoTable.person_card);
            if (info != null) {
                mongoBaseDao.updateOne(param, user.toDBObject().toMap(), MongoTable.person_card);
            } else {
                mongoBaseDao.insert(user, MongoTable.person_card);
            }
            this.success(res);
        } catch (BizException ex) {
            LOGGER.info("occur biz error : {} ", ex);
            this.failed(res, ex);
        } catch (Exception e) {
            LOGGER.error("occur error", e);
            this.failed(res, "操作失败，请重试或者联系管理员解决!");
        }
        return res;
    }


    @ResponseBody
    @RequestMapping(value = "/info")
    public Map personInfo(@RequestParam String code) {
        Map res = new HashMap();
        try {
            Map param = new BasicDBObject("code", code).toMap();
            PersonInfo info = (PersonInfo) mongoBaseDao.findOne(param, PersonInfo.class, MongoTable.person_card);
            res.put("data", info);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.info("occur biz error : {} ", ex);
            this.failed(res, ex);
        } catch (Exception e) {
            LOGGER.error("occur error", e);
            this.failed(res, "操作失败，请重试或者联系管理员解决!");
        }
        return res;
    }



}
